/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uk.ac.cam.can.watermarking.algorithm;

import uk.ac.cam.can.watermarking.misc.DataSet;
import java.util.Random;

/**
 *
 * @author Thomas
 */
public class AKH implements WatermarkingAlgorithm{
    public static final int PERIOD = 3;
    public static final int ALTERABLE = 3;
    @Override
    public DataSet mark(DataSet data, long key) {
        System.out.println("Mark");
        // for all datasets
        for(int i = 0; i < data.size(); i++){
            long seed = key+Long.parseLong(data.getAttribute(i, 0));
            Random rand = new Random(seed);
            if(rand.nextInt(PERIOD)==0){
                int position = rand.nextInt(ALTERABLE);
                int bit = rand.nextInt(2); // 0 or 1
                System.out.println(i+"-"+position+"-"+bit);
                int a = Integer.parseInt(data.getAttribute(i, 1));
                if(bit==1)
                    a = setBitValue(a, position, true);
                else
                    a = setBitValue(a, position, false);
                data.setAttribute(i, 1, Integer.toString(a));
            }
        }
        return data;
    }
    
    @Override
    public float checkMark(DataSet data, long key){
        System.out.println("Check mark");
        int tot=0;
        int found=0;
        for(int i = 0; i < data.size(); i++){
            long seed = key+Long.parseLong(data.getAttribute(i, 0));
            Random rand = new Random(seed);
            if(rand.nextInt(PERIOD)==0){
                tot++;
                int position = rand.nextInt(ALTERABLE);
                int bit = rand.nextInt(2); // 0 or 1
                int a = Integer.parseInt(data.getAttribute(i, 1));                
                System.out.println(i+"-"+position+"-"+bit);
                int v = 0;
                if(bit==1)
                    v = setBitValue(a, position, true);
                else
                    v = setBitValue(a, position, false);
                if(v==a)
                    found++;
            }
        }
        return (float)found/(float)tot;
    }
    
    private int setBitValue(int number, int position, boolean bit){
        int tmp=0;
        if(bit==true){
            tmp = (int) (number | (1 << position));
        }else{
            tmp = (int) (number & ~(1 << position));
        }
        return tmp;
    }
    
}
